package business.util;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class MonetarioDocument extends PlainDocument
{
	private static final long serialVersionUID = 8491462133943487109L;
	public static final int NUMERO_DIGITOS_MAXIMO = 14;

	public void insertString(int offs, String str, AttributeSet a) throws BadLocationException 
	{
		String strAux = str;
		String decimal = "";
		
		if( (strAux.length() > 1) && (offs != 2))
		{
			if(str.indexOf(".") >= 0)
				decimal = str.substring(str.indexOf("."), str.length());
			
			if(decimal.length() == 2)
			{
				strAux += "0";
			}
			else
			if(decimal.length() == 1 )
			{
				strAux += "00";
			}
			else
			if(decimal.length() == 0 )
			{
				strAux += ".00";
			}
		}
		
		for(int i = 0; i < strAux.length(); i++)
		{
			str = String.valueOf(strAux.charAt(i));
			
			String texto = getText(0, getLength());
		
			if(str.length() == 1)
			{
				char c = str.charAt(0);
				if (!Character.isDigit(c)) 
				{
					continue;
				}
			}
			
	
			if(texto.length() < NUMERO_DIGITOS_MAXIMO)
			{
				super.remove(0, getLength());
				texto = texto.replace(".", "").replace(",", "");
				StringBuffer s = new StringBuffer(texto + str);
			
				if (s.length() > 0 && s.charAt(0) == '0') 
				{
					s.deleteCharAt(0);
				}
		
				if(s.length() < 3) 
				{
					if (s.length() < 1) 
					{
						s.insert(0,"000");
					} 
					else 
					if (s.length() < 2) 
					{
						s.insert(0,"00");
					} 
					else 
					{
						s.insert(0,"0");
					}
				}
		
				s.insert(s.length()-2, ",");
		
				if(s.length() > 6) 
				{
					s.insert(s.length()-6, ".");
				}
		
				if(s.length() > 10) 
				{
					s.insert(s.length()-10, ".");
				}
		
				super.insertString(0, s.toString(), a);
			}
		}
	}

	public void remove(int offset, int length) throws BadLocationException 
	{
		super.remove(offset, length);
		String texto = getText(0, getLength());
		texto = texto.replace(",", "");
		texto = texto.replace(".", "");
		super.remove(0, getLength());
		this.insertString(2, texto, null);
	}

}
